package com.seven.netty.protocol.handler;

import com.seven.netty.protocol.bean.Head;
import com.seven.netty.protocol.bean.Message;
import com.seven.netty.protocol.constants.NettyConstant;
import com.seven.netty.protocol.enums.MessageTypeEnum;
import com.seven.netty.protocol.server.DemoTest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author chendongdong
 * @description 心跳处理
 * @since 2024/3/6 10:53
 */
@Slf4j
public class ClientHeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("heart beat error ", cause);
        super.exceptionCaught(ctx,cause);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("断线了......" + ctx.channel().id());
        ctx.channel().eventLoop().schedule(() -> {
            log.info("断线重连......");
            //重连
            DemoTest.connect();
        }, 5L, TimeUnit.SECONDS);
    }
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Message message = new Message();
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                log.info("客户端心跳检测 发送心跳包数据");
                Head head = Head.builder()
                    .headIndex(NettyConstant.HEAD_INDEX)
                    .crcCode(NettyConstant.CRC_CODE)
                    .version(NettyConstant.VERSION)
                    .sessionId(32L)
                    .messageType(MessageTypeEnum.HEARTBEAT_REQUEST.getType().byteValue())
                    .length(NettyConstant.HEAD_LENGTH).build();
                message.setHead(head);
                ctx.writeAndFlush(message);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
